package airplane.com.example.service;

import airplane.com.example.entry.Airplane;
import airplane.com.example.mapper.AirplaneMapper;
import airplane.com.example.mapper.TicketMapper;
import airplane.com.example.utilities.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class AirplaneServiceImpl implements AirplaneService {
    @Autowired
    private AirplaneMapper airplaneMapper;

    @Autowired
    private TicketMapper ticketMapper;

    @Override
    public Result addAirplane(Airplane airplane) {
        try {
            if(airplaneMapper.queryAirplaneByName(airplane.getAirplane()) != null)
                return new Result("班次已存在!", false);
            airplaneMapper.insertAirplane(airplane);
            return new Result("添加成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("系统错误：添加机票信息失败!", false);
        }

    }

    @Override
    public Result updateAirplane(Airplane airplane) {
        try {
            airplaneMapper.updateAirplane(airplane);
            return new Result("更新成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("系统错误：更新机票信息失败!", false);
        }
    }

    @Override
    public Result deleteAirplane(String airplane) {
        try {
            airplaneMapper.deleteAirplane(airplane);
            ticketMapper.deleteTicketAllByAirplane(airplane);
            return new Result("删除成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("系统错误：删除机票信息失败!", false);
        }
    }

    // 分页查询
    @Override
    public List<Airplane> findByPage(Integer currentPage, Integer pageSize) {
        currentPage = (currentPage - 1) * pageSize;
        return airplaneMapper.findByPage(currentPage, pageSize);
    }

    // 查询总页数
    @Override
    public int findTotal() {
        return airplaneMapper.findTotal();
    }
}
